/**
 * Created by seth.yang on 2016/9/13
 */
(function ($) {
    if (!$) return;
    if ($.fn.asDropdown) return;

    var handlers = {}, holders = {}, hideMenu = function (ul, target) {
        if (!handlers [target]) {
            handlers[target] = setTimeout (function () {
                closeOptions (ul, target);
            }, 500);
        }
    },closeOptions = function (panel, target) {
        var label = panel.data ('label');
        label.attr ('data-state', 'closed').addClass ('dropdown-list-outline-down-arrow').removeClass ('dropdown-list-outline-up-arrow');
        panel.hide ();
        delete handlers [target];
    }, onSelectionChanged = function () {
        var self = $(this), ul = self.closest ('ul'), target = ul.attr ('data-for'),
            select = $('#' + target), value = self.attr ('data-value'), div = ul.data ('label');
        for (var i = 0; i < select [0].options.length; i ++) {
            var v = select [0].options [i].value;
            if (v == value) {
                select[0].selectedIndex = i;
                select[0].options [i].checked = 'checked';
                div.text (select [0].options [i].text);
                closeOptions (ul, target);
                if (holders [target]/* && holders [target].selectedIndex != i*/) {
                    holders [target].selectedIndex = i;
                    select.trigger ('change');
                }
                break;
            }
        }
    }, onDivMouseOut = function () {
        var self = $(this), ul = self.data ('body'), target = self.attr ('data-for');
        hideMenu (ul, target);
    },onMouseOut = function () {
        var self = $(this), ul = self.closest ('ul'), target = ul.attr ('data-for');
        hideMenu (ul, target);
    }, onMouseIn = function () {
        var self = $(this), ul = self.closest ('ul'), target = ul.attr ('data-for');
        if (handlers [target]) {
            clearTimeout (handlers [target]);
            delete handlers [target];
        }
    };

    function onDataSourceChanged (ul, source) {
        ul.empty ();
        var label = ul.data ('label');
        for (var i = 0; i < source.options.length; i ++) {
            var li = $('<li/>').appendTo (ul);
            $('<a class="option-item"/>').appendTo (li).attr ('data-value', source.options [i].value)
                .text (source.options[i].text).on ('click', onSelectionChanged)
                .on ('mouseover', onMouseIn).on ('mouseout', onMouseOut);
            if (source.options [i].selected) {
                // selectedText = source.options [i].text;
                if (label) {
                    label.text (source.options [i].text);
                }
                source.selectedIndex = i;
            }
        }

        if (source.options.length && (!source.selectedIndex || source.selectedIndex == -1)) {
            if (label) {
                label.text (source.options [0].text);
            }
        }
    }

    $.fn.asDropdown = function (options) {
        this.fireDataChange = function () {
            var self = holders [this.attr ('id')];
            if (self) {
                self.val ('');
                var body = self.data ('body');
                onDataSourceChanged (body, self [0]);
            }
        };
        return $(this).each (function () {
            var self = $(this), parent = self.parent ();
            if (parent) {
                self.hide ();
                holders [this.id] = self; // cache the jQuery Object.
                $('#outline-' + this.id).remove ();
                $('#list-' + this.id).remove ();
                var div = $('<div class="text dropdown-list-outline dropdown-list-outline-down-arrow"/>')
                    .attr ({
                        'data-state':'closed',
                        'data-for':this.id,
                        id: 'outline-' + this.id
                    }).on ('click', function () {
                        var self = $(this), body = self.data ('body'), state = self.attr ('data-state');
                        if (body) {
                            if (state == 'closed') {
                                body.show ();
                                var offset = parent.position ();
                                var h = parent.height ();
                                var h_t = parseInt (parent.css ('padding-top'), 10),
                                    h_b = parseInt (parent.css ('padding-bottom'), 10),
                                    b_t = parseInt (parent.css ('border-top-width'), 10),
                                    b_b = parseInt (parent.css ('border-bottom-width'), 10),
                                    m_t = parseInt (parent.css ('margin-top'), 10),
                                    m_b = parseInt (parent.css ('margin-bottom'), 10);
                                if (h_t) h += h_t;
                                if (h_b) h += h_b;
                                if (b_t) h += b_t;
                                if (b_b) h += b_b;
                                if (m_t) h += m_t;
                                if (m_b) h += m_b;
                                body.css ({left:offset.left,top:offset.top + h});
                                self.removeClass ('dropdown-list-outline-down-arrow')
                                    .addClass ('dropdown-list-outline-up-arrow')
                                    .attr ('data-state', 'opened');
                            } else {
                                body.hide ();
                                self.addClass ('dropdown-list-outline-down-arrow')
                                    .removeClass ('dropdown-list-outline-up-arrow')
                                    .attr ('data-state', 'closed')
                            }
                        }
                    }).on ('mouseout', onDivMouseOut).appendTo (parent),
                    w = parent.width (),
                    leftPadding = parseInt (parent.css ("padding-left")),
                    rightPadding = parseInt (parent.css ('padding-right'));
                if (leftPadding) w += leftPadding;
                if (rightPadding) w += rightPadding;
                var ul = $('<ul class="dropdown-list-body"/>')
                    .css ('width', w)
                    .attr ({
                        'data-for': this.id,
                        id:'list-' + this.id
                    }).appendTo (parent);
                div.data ('body', ul);
                ul.data ('label', div);
                self.data ('body', ul);
/*
                var pt = parseInt (parent.css ('padding-top'), 10),
                    pb = parseInt (parent.css ('padding-bottom'), 10),
                    bt = parseInt (parent.css ('border-top-width'), 10),
                    bb = parseInt (parent.css ('border-bottom-width'), 10),
                    height = parent.height ();
                if (pt) height -= pt;
                if (pb) height -= pb;
                if (bt) height -= bt;
                if (bb) height -= bb;
*/
                var height = parent.height ();
                div.css ({'height':height, 'line-height':height+'px'});
                //var selectedText = '';
                onDataSourceChanged (ul, this);
                var selectedText = this.options [this.selectedIndex].text;
                if (selectedText == '') {
                    selectedText = this.options [0].text;
                }
                div.text (selectedText);
            }
        });
    };
})(jQuery);